package com.xy6.concurrencyart.chapter02;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * CAS机制示例
 * 
 * @author zhang
 * @since 2018-05-21
 */
public class Counter {

	private AtomicInteger atomicI = new AtomicInteger(0);
	private int i = 0;

	public static void main(String[] args) {
		final Counter cas = new Counter();
		List<Thread> ts = new ArrayList<>(600);
		long time1 = System.currentTimeMillis();
		for (int i = 0; i < 100; i++) {
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					for (int i = 0; i < 10000; i++) {
						cas.count();
						cas.safeCount();
					}
				}
			});
			ts.add(t);
		}
		for (Thread t : ts) {
			t.start();
		}
		// 等待所有线程执行结束
		for (Thread t : ts) {
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// < 1000000
		System.out.println(cas.i);
		// 1000000
		System.out.println(cas.atomicI.get());
		System.out.println(System.currentTimeMillis() - time1);
	}

	/**
	 * 非线程安全计数器
	 */
	private void count() {
		i++;
	}
	
	/**
	 * 线程安全计数器。CAS实现i++
	 */
	private void safeCount(){
		for(;;){
			int i = atomicI.get();
			boolean result = atomicI.compareAndSet(i, ++i);
			if(result){
				break;
			}
		}
	}

}
